import key from 'keymaster'

import { asyncTopicConstants } from '../constants/asyncTopicConstants'
import { syncTopicConstants } from '../constants/syncTopicConstants'
import hotkeys from 'hotkeys-js';

import * as service from '../utils/request'


const GlobalModel = {
    namespace: 'global',
    state: {
        searchDataSource: "pluginDefine",     // configDefine:搜索结果来自配置定义或动态生成，动态生成通常是list模式下的搜索结果
        containerType: "list",                // list：列表， page：融合模式下的页面
        slogan: null,                         // 搜索的slogan
        avatar: null,                         // 用户头像
        iconType: "keyword",                  // 搜索方式
        extInfo: null,                        // 搜索方式
        subInput: null,                       // 搜索方式
        keyword: "",                          // 当前搜索关键字
        preSearchPosition: { x: 0, y: 0 },    // 预搜索的显示位置
        preSearch: null,                      // 预搜索的显示内容
        placeholder: "",                      // list的placeholder
        keys: [],                             // 记录最后按的几个键

    },
    effects: {


        *initSearch({ payload, callback }, { call, put, select }) {
            service.onEmit(asyncTopicConstants.setHeight, 60)
        },

        *initSearchHeigth({ payload, callback }, { call, put, select }) {
            service.onEmit(asyncTopicConstants.setHeight, 60)
        },

        *setPreSearchPosition({ payload, callback }, { call, put, select }) {
            yield put({ type: 'save', payload: { preSearchPosition: payload } })
        },

        *getSlogan({ payload, callback }, { call, put, select }) {
            const response = yield call(service.request, syncTopicConstants.getSlogan, null)
            if (response.success) {
                yield put({ type: 'save', payload: { slogan: response.body.slogan } })
            }
        },
        *getAvatar({ payload, callback }, { call, put, select }) {
            const response = yield call(service.request, syncTopicConstants.getAvatar, null)
            if (response.success) {
                yield put({ type: 'save', payload: { avatar: response.body.avatar } })
            }
        },

        *doSearchPlugin({ keyword, callback }, { call, put, select }) {
            if (keyword == "") {
                service.onEmit(asyncTopicConstants.setHeight, 60)
                service.onEmit(asyncTopicConstants.doEmptySearchResult)
            } else {
                const state = yield select(state => state.global)
                let payload = { type: state.iconType, subInput: state.subInput, input: keyword, extInfo: state.extInfo, source: "search" }
                service.onEmit(asyncTopicConstants.doSearchPlugin, payload)

            }
            yield put({ type: "save", payload: { keyword: keyword, } })

        },


        *doKeyUpBackspace({ payload, callback }, { call, put, select }) {
            const { keyword, subInput, iconType } = yield select(state => state.global)
            // 响应有subInput情况下继续删除，回到初始状态
            if (keyword == "") {
                yield put({ type: "save", payload: { subInput: "", preSearch: "", iconType: "keyword", } })
                // 如果不是keyword模式下需要对view进行重置，避免fusion模式下污染view
                if (iconType != "keyword") {
                    service.onEmit(asyncTopicConstants.resetMainWinView)
                }
            }
        },

        *doKeyUpEsc({ payload, callback }, { call, put, select }) {
            const { keyword } = yield select(state => state.global)
            // 响应有subInput情况下继续删除，回到初始状态
            if (keyword == "") {
                service.onEmit(asyncTopicConstants.hideMain)
            } else {
                yield put({ type: "save", payload: { keyword: "" } })
                document.getElementById("input").value = ""
            }
        },

        *doCopyPreSearch({ payload, callback }, { call, put, select }) {
            const { keys, preSearch } = yield select(state => state.global)
            const theKey = keys.pop();

            if (theKey != undefined) {
                console.info("doCopyPreSearch", theKey.code, preSearch.data)
                if (theKey.code == "KeyC" && preSearch != "") {
                    service.onEmit(asyncTopicConstants.copyToClipboard, { content: preSearch.data })
                }
            }
        },


        *doRecordKey({ payload, callback }, { call, put, select }) {
            const key = payload.key
            let { keys } = yield select(state => state.global)
            keys.push(key)
            let newKeys = []
            for (let i = 0; i < 3; i++) {
                let theKey = keys.pop()
                if (theKey != undefined) {
                    newKeys.push(theKey)
                }
            }
            newKeys.reverse()
            yield put({ type: "save", payload: { keys: newKeys } })
        },


    },
    reducers: {
        save(state, { payload }) {
            return { ...state, ...payload };
        },


    },
    subscriptions: {
        onPreSearch({ dispatch }) {
            return service.onListen(asyncTopicConstants.onPreSearch,
                (response) => {
                    if (response.success == true) {
                        dispatch({ type: 'save', payload: { preSearch: response.body } })
                    }
                }
            )
        },

        /*
        * desc: 主渲染窗口拿到点击运行窗口后，需要设置上下文
        */
        onTriggerForListPlugin({ dispatch }) {
            return service.onListen(asyncTopicConstants.onTriggerForListPlugin,
                (response) => {
                    if (response.success == true) {
                        dispatch({
                            type: 'save', payload: {
                                searchDataSource: "codeDefine",
                                keyword: "",
                                subInput: response.body.payload.plugin.cmdInfo.featureInfo.name,
                                iconType: "listPlugin",
                            }
                        })
                    }
                }
            )
        },

        /*
        * desc: 主渲染窗口拿到点击运行窗口后，需要设置上下文
        */
        onTriggerForFusionPlugin({ dispatch }) {
            return service.onListen(asyncTopicConstants.onTriggerForFusionPlugin,
                (response) => {
                    if (response.success == true) {
                        dispatch({
                            type: 'save', payload: {
                                searchDataSource: "pluginDefine",
                                keyword: "",
                                subInput: response.body.payload.plugin.cmdInfo.featureInfo.name,
                                iconType: "fusionPlugin",
                            }
                        })
                    }
                }
            )
        },


        /*
        * 主渲染进程监听键盘事件，发送消息给view进行事件执行
        */
        onKeyUp({ dispatch }) {
            document.addEventListener("keyup", (key) => {
                if (key.code == "ArrowDown" | key.code == "ArrowUp") {
                    service.onEmit(asyncTopicConstants.onKeyUpOrDown, { keyCode: key.code })
                } else if (key.code == "Enter") {
                    service.onEmit(asyncTopicConstants.onKeyEnter)
                } else if (key.code == "Backspace") {
                    dispatch({ type: 'doKeyUpBackspace' })
                } else if (key.code == "Escape") {
                    dispatch({ type: 'doKeyUpEsc' })
                }
            })

        },


        /*
        * 主渲染进程监听键盘事件，发送消息给view进行事件执行
        */
        onKeyDown({ dispatch }) {
            document.addEventListener("keydown", (key) => {
                // 记录所有按键，只保存最后3个
                dispatch({ type: 'doRecordKey', payload: { key: key } })
                // 按住C键时   
                if (key.code == "KeyC") {
                    dispatch({ type: 'doCopyPreSearch' })
                }
            })
        },

        /*
        * 监听list插件设置的placeholder
        */
        onSetListPluginPlaceholder({ dispatch }) {
            return service.onListen(asyncTopicConstants.doSetListPluginPlaceholder,
                (response) => {
                    dispatch({ type: 'save', payload: { placeholder: response.payload } })
                }
            )
        }
    }


};


export default GlobalModel;
